//
//  UIImage+QRCode.m
//  XianjinXia
//
//  Created by liu xiwang on 2017/7/26.
//  Copyright © 2017年 lxw. All rights reserved.
//

#import "UIImage+QRCode.h"
#import <CoreImage/CoreImage.h>

@implementation UIImage (QRCode)

+(UIImage *)creatNormalQRCodeWithStr:(NSString *)string{
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setDefaults];
    NSString * strQR = [string isEqualToString:@""] ? @"http://www.kxqianbao.com" : string;
    NSData *data = [strQR dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    CIImage *outputImg = [filter outputImage];
    
    return [self imageWithCIImage:outputImg];
}

+(UIImage *)creatHighdefinQRCodeWithStr:(NSString *)string withSize:(CGFloat) size{
    CIImage *image = [[self creatNormalQRCodeWithStr:string] CIImage];
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

+(UIImage *)creatHighdefinQRCodeWithStr:(NSString *)string withLogo:(UIImage *)logo withSize:(CGFloat)size{

    UIImage * useImage = [self creatHighdefinQRCodeWithStr:string withSize:size];
    
    UIGraphicsBeginImageContextWithOptions(useImage.size ,NO, 0.0);
    [useImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height)];
    
    CGFloat centerW=logo.size.width;
    CGFloat centerH=logo.size.height;
    CGFloat centerX=(useImage.size.width-centerW)*0.5;
    CGFloat centerY=(useImage.size.height -centerH)*0.5;
    
    //四个参数为水印图片的位置
    [logo drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultingImage;
}

@end
